package com.focus.xyz.union.pages.backend;

import com.focus.xyz.core.common.keyword.Action;
import com.focus.xyz.core.pages.BaseMenu;
import com.focus.xyz.core.utils.Constants;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

import java.util.List;

/**
 * Created by chenmeng on 2016/4/14.
 */
public class BackMenuList extends BaseMenu {
    private Action action;
    @FindBy(id = "dev_accordion")
    private WebElement menuListPane;

    @FindBy(tagName = "iframe")
    private WebElement menuFrame;
    private static final String PARENT_MENU_XPATH = "//*/div[@class='panel-body accordion-body']";
    private static final String MENU_XPATH = "ul/li/a";
    private static final String UNCLE_MENU_XPATH = "../div[1]";
    private static final String EXPAND_PARENT_MENU_LINK = "../div[1]/*/a";

    public BackMenuList(WebDriver driver,Action action){
        super(driver,action);
        this.action = action;
        PageFactory.initElements(driver,this);
    }


    /*
    * 根据父菜单链接名称、菜单链接名称打开菜单，适用于渠道后台菜单
    * */
    @Override
    public void openExpandMenu(String parentName,String name) throws Exception{
        List<WebElement> parentMenuList = menuListPane.findElements(By.xpath(PARENT_MENU_XPATH));
        for(WebElement pMenu:parentMenuList){
            if(parentName.equals(pMenu.findElement(By.xpath(UNCLE_MENU_XPATH)).getText())){
                if(pMenu.getAttribute(Constants.ATTR_STYLE).toLowerCase().contains("display: none")){
                    WebElement expandLink = pMenu.findElement(By.xpath(EXPAND_PARENT_MENU_LINK));
                    action.click(expandLink);
                    action.pause(1000l);
                }
                List<WebElement> menuList = pMenu.findElements(By.xpath(MENU_XPATH));
                for(WebElement menu:menuList){
                    if(name.equals(menu.getText())){
                        action.click(menu);
                        action.pause(1000l);
                        switchToMenuFrame();
                        break;
                    }
                }
                break;
            }

        }
    }

    @Override
    public void openMenu(String name) throws Exception{

    }

    private void switchToMenuFrame() throws Exception{
        action.switchToFrame(menuFrame);
    }
}
